<?php
/**
 * 小蜗牛留言本
 * 本文件内代码属于“小蜗牛留言本”项目，禁止修改再发布本程序源码，禁止去除页面底部的版权申明。所有版权保留
 * User: upliu
 * Email: 753073861@qq.com
 * QQ: 753073861
 * 程序主页：http://demo.upliu.net/snail-guestbook/
 */

require __DIR__ . '/init.php';

if (is_installed()) {
    die('已经安装过，如果要重新安装请先删除配置文件：' . realpath(__DIR__.'/config.php'));
}

$not_pass_check = install_not_filled_requirements();

if (!empty($not_pass_check)) {
    echo "<h1>小蜗牛留言本</h1>";
    echo "<h2>安装之前，以下问题必须解决：</h2>";
    foreach ($not_pass_check as $error) {
        echo "<p>$error</p>";
    }
    exit();
}

if (empty($_POST)) {
    echo get_install_html();
    exit();
}

$config = array(
    'host'=> $_POST['host'],
    'dbname' => $_POST['dbname'],
    'port' => $_POST['port'],
    'username' => $_POST['username'],
    'password' => $_POST['password'],
);

$db = Db::getInstance($config);
try {
    $db->getConnection();
} catch (\PDOException $e) {
    echo get_install_html('数据库连接失败：' . $e->getMessage());
    exit();
}

install_init_db();

$username = 'xiaowoniu';
$password = 'xiaowoniu';
add_admin_user($username, $password, 0);

install_save_config($config);

echo get_after_install_html();
exit();

function install_not_filled_requirements()
{
    $result = array();
    if (!is_writable(__DIR__)) {
        $result[] = sprintf("目录 %s 无法写入", __DIR__);
    }

    if (!class_exists('PDO') || !in_array('mysql', PDO::getAvailableDrivers(), true)) {
        $result[] = sprintf("PDO_MYSQL 扩展必须打开");
    }

    return $result;
}

function get_install_html($error = '')
{
    $default_config = array(
        'host' => 'localhost',
        'port' => 3306,
        'dbname' => '',
        'username' => 'root',
        'password' => '',
    );
    $config = array_merge($default_config, $_POST);
    extract($config);

    $table_name = implode(', ', install_get_table_names());

    return <<<EOT
<!doctype html>
<html>
<head><meta charset="utf-8"><title>安装-小蜗牛留言本</title></head>
<body>
<h1>小蜗牛留言本</h1>
<div style="color:red;">$error</div>
<form method="post">
<table>
    <tr><td>MySQL主机地址：</td><td><input type="text" name="host" value="$host"></td></tr>
    <tr><td>MySQL端口：</td><td><input type="text" name="port" value="$port"></td></tr>
    <tr><td>MySQL数据库名：</td><td><input type="text" name="dbname" value="$dbname"></td></tr>
    <tr><td>MySQL用户名：</td><td><input type="text" name="username" value="$username"></td></tr>
    <tr><td>MySQL密码：</td><td><input type="password" name="password" value="$password"></td></tr>
</table>
<p><input type="submit" value="开始安装">请注意，小蜗牛留言本数据表名为 {$table_name}，如果您的数据库中已经存在同名的表，将会被删除。</p>
</form>
</body>
</html>
EOT;

}

function get_after_install_html()
{
    global $username, $password;
    return <<<EOT
<!doctype html>
<html>
<head><meta charset="utf-8"><title>安装-小蜗牛留言本</title></head>
<body>
<h1>小蜗牛留言本</h1>
<h2>安装成功</h2>
<p>访问前台:<a target="_blank" href="index.php">index.php</a></p>
<p>访问后台:<a target="_blank" href="admin/index.php">admin/index.php</a> 用户名：$username 密码：$password</p>
</form>
</body>
</html>
EOT;
}

function install_get_table_names()
{
    return array(
        'admin_dept',
        'admin_user',
        'note',
        'note_reply',
    );
}

function install_init_db()
{
    $db = Db::getInstance();

    foreach (install_get_table_names() as $table) {
        $db->execute("drop table if exists $table");
    }

    $db->execute("CREATE TABLE `admin_dept` (
  `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
  `name` varchar(20) NOT NULL DEFAULT '',
  `is_show` tinyint(4) NOT NULL DEFAULT '1',
  PRIMARY KEY (`id`),
  UNIQUE KEY `name` (`name`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;");

    $db->execute("CREATE TABLE `admin_user` (
  `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
  `dept_id` int(11) NOT NULL COMMENT '如果为0，则是管理员',
  `username` varchar(20) NOT NULL DEFAULT '',
  `salt` char(6) NOT NULL DEFAULT '',
  `password` varchar(32) NOT NULL DEFAULT '',
  `status` int(11) NOT NULL DEFAULT '10' COMMENT '用户状态，10=可用，20=禁用',
  PRIMARY KEY (`id`),
  UNIQUE KEY `username` (`username`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;");

    $db->execute("CREATE TABLE `note` (
  `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
  `nickname` varchar(20) NOT NULL,
  `content` text NOT NULL,
  `qq` varchar(15) NOT NULL DEFAULT '',
  `email` varchar(25) NOT NULL DEFAULT '',
  `create_time` datetime NOT NULL,
  `ip` int(10) unsigned NOT NULL,
  `is_replied` tinyint(4) NOT NULL DEFAULT '0' COMMENT '是否回复',
  `dept_id` int(11) NOT NULL DEFAULT '0',
  PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;");

    $db->execute("CREATE TABLE `note_reply` (
  `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
  `content` text NOT NULL,
  `user_id` int(11) NOT NULL,
  `dept_id` int(11) NOT NULL,
  `reply_note_id` int(11) NOT NULL COMMENT '被回复的留言 ID',
  `create_time` datetime NOT NULL,
  PRIMARY KEY (`id`),
  KEY `reply_note_id` (`reply_note_id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;");
}

function install_save_config($config)
{
    $config_file_path = __DIR__ . '/config.php';
    file_put_contents($config_file_path, "<?php\nreturn " . var_export($config, true) . ";\n");
}